import _ from 'lodash'
import {onMounted, onUnmounted, ref, watch} from "vue";
import { $bus } from '@jzl/utils'

// def defPath
export function useMaskHover(props, emit) {

  // let interval = null;
  const elements = ref([]);
  let masks = [];

  // 创建高亮框和调整大小的手柄
  function createMask(el) {
    const mask = document.createElement("div");
    mask.className = "builder-mask";

    fixMaskPosition(mask, el)
    document.body.appendChild(mask);
    return mask;
  }

  const fixMaskPosition = (mask, el) => {
    const rect = el?.getBoundingClientRect();

    mask.style.display = 'block';
    mask.style.left = `${ rect?.left }px`;
    mask.style.top = `${ rect?.top }px`;
    mask.style.width = `${ rect?.width }px`;
    mask.style.height = `${ rect?.height }px`;
  }

  const refreshMask = _.throttle(() => {
    let els = elements.value;
    if(els?.length < masks.length) {
      for(let i = els.length; i < masks.length; i++) {
        masks[i].style.display = 'none';
      }
    }
    for(let i = 0; i < els.length; i++) {
      let el = els[i];
      let mask = masks[i];
      if(!mask) {
        mask = createMask(el);
        masks[i] = mask;
      }

      fixMaskPosition(mask, el)
    }
  }, 500)

  const clearMask = () => {
    masks?.forEach(del => {
      del.remove();
    })
  }

  const initMask = () => {
    let hoverCode = props.hoverElCode;
    if(!hoverCode) {
      elements.value = []
    } else {
      elements.value = (props.container || document).querySelectorAll(`[j-name=${hoverCode}]`);
    }

    refreshMask()
  }

  watch(
    () => props.hoverElCode,
    () => initMask()
  );

  onMounted(() => {
    /*if (typeof window !== 'undefined') {
      window.addEventListener('resize', _refreshMask)
    }
    interval = setInterval(refreshMask, 500) */

    $bus.on('design:clearHoverMask', clearMask)
  });

  onUnmounted(() => {
    // window.removeEventListener('resize', refreshMask)
    clearMask()
    $bus.off('design:removeHoverMask', clearMask)
  });

  return {
    refreshMask,
    clearMask
  }
}
